package main

import (
	"fmt"
	"match-spider/util/prop"
	"time"
	"github.com/gocolly/colly"
	"github.com/PuerkitoBio/goquery"
	"strings"
	"match-spider/util/boltdb"
	"math/rand"
)

/**
抓取比赛
 */
func fetchMatch(dbKey string,date string)  {
	url:="http://bf.win007.com/Over_matchdate.aspx?matchdate="+date

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnHTML("#table_live", func(e *colly.HTMLElement) {

		e.DOM.Find("tr").Each(func(i int, s *goquery.Selection){
			d := s.Find("td").Eq(9)
			text, b := d.Find("a").Eq(0).Attr("onclick")
			if b {
				id := strings.Replace(text, "analysis(", "", -1)
				id = strings.Replace(id, ")", "", -1)
				league := s.Find("td").Eq(0).Text()
				datetime:=s.Find("td").Eq(1).Text()
				homeTeam:=s.Find("td").Eq(3).Text()
				d3 := s.Find("td").Eq(4)
				homeScore := d3.Find("font").Eq(0).Text()
				guestSocre := d3.Find("font").Eq(1).Text()
				guestTeam:=s.Find("td").Eq(5).Text()
				asiaOdds:=s.Find("td").Eq(7).Text()
				underOverOdds := s.Find("td").Eq(8).Text()
				//fmt.Println(datetime,id,league,date,homeTeam,homeScore,guestTeam,guestSocre,asiaOdds,underOverOdds)
				m:=id+"^"+league+"^"+datetime+"^"+homeTeam+"^"+homeScore+"^"+guestTeam+"^"+guestSocre+"^"+asiaOdds+"^"+underOverOdds
				bucket:=strings.Replace(date,"-","",-1)

				boltdb.Put(dbKey,bucket,id,m)
			}

		})
	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)
	})

	c.Visit(url)
}

func main()  {
	startAt:=prop.Get("match","date.start")
	endAt:=prop.Get("match","date.end")
	startTime,_:=time.Parse("2006-01-02",startAt)
	endTime,_:=time.Parse("2006-01-02",endAt)

	for{
		if(endTime.Sub(startTime).Hours()<0){
			break
		}

		nextTimeString:=time.Unix(startTime.Unix(),0).Format("2006-01-02")
		fetchMatch("matchs",nextTimeString)
		seed:=200+rand.Intn(300)
		time.Sleep(time.Millisecond*time.Duration(seed))
		startTime=startTime.Add(time.Hour*24)
	}

}
